<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <base href="/">
  <meta charset="UTF-8">
  <title>订单管理</title>
  <link rel="stylesheet" href="layui/css/layui.css">
  <style>
    /* 新增表格容器样式 */
    .table-container {
      overflow: hidden;
      margin: 15px;
    }
    .layui-table tr{
      height: auto;
    }
    /* 单元格自适应高度 */
    .layui-table-cell {
      height: auto !important;
      min-height: 52px;
      white-space: normal;
      padding: 8px 10px;
      line-height: 1.5;
    }
    /* 操作按钮样式 */
    .layui-table-tool .layui-btn {
      margin: 2px;
      padding: 0 8px;
      height: 28px;
      line-height: 28px;
    }
    /* 操作按钮容器样式 */
    .layui-table-tool-temp {
      padding: 5px 0 !important;
    }
    /* 按钮统一样式 */
    .layui-table .layui-btn {
      min-width: 50px;
      height: 28px;
      line-height: 28px;
      padding: 0 8px;
      font-size: 12px;
      border-radius: 3px;
      white-space: nowrap;
    }
    /* 鼠标悬停效果 */
    .layui-table .layui-btn:hover {
      opacity: 0.9;
      transform: translateY(-1px);
    }

    /* 固定列样式覆盖 */
    .layui-table-fixed {
      box-shadow: -2px 0 6px rgba(0,0,0,.08);
    }

    /* 订单详情弹窗样式 */
    .order-detail-dialog {
      padding: 20px;
    }

    /* 商品项样式 */
    .product-item {
      display: flex;
      align-items: center;
      border-bottom: 1px solid #e2e2e2;
      padding: 15px 0;
    }

    /* 商品图片样式 */
    .product-image {
      width: 100px;
      height: 100px;
      object-fit: cover;
      margin-right: 20px;
      border-radius: 5px;
    }

    /* 商品信息样式 */
    .product-info {
      display: flex;
      flex-direction: column;
    }

    /* 商品信息项样式 */
    .product-info span {
      margin-bottom: 5px;
      font-size: 14px;
    }
  </style>
</head>
<body>
<!--数据列表-->
<div class="table-container">
  <table class="layui-table" lay-data="{
    url:'order/getOrders',
    page:true,
    id:'datalist',
    toolbar:'#toptools',
    scrollX: true,
    parseData: function(res){
      return {
        code: res.code,
        msg: res.msg,
        count: res.count,
        data: res.data
      };
    }
  }" lay-filter="datalist">
    <thead>
    <tr>
      <th lay-data="{field:'name', width:120}">用户姓名</th>
      <th lay-data="{field:'ordertime', width:160, templet: function(d){ return formatTime(d.ordertime); }}">下单时间</th>
      <th lay-data="{field:'money', width:100}">订单金额</th>
      <th lay-data="{field:'status', width:100}">订单状态</th>
      <th lay-data="{field:'code', width:160}">订单号</th>
      <th lay-data="{field:'isupset', templet: '#isupsetTpl', width:120}">是否上门安装</th>
      <th lay-data="{field:'addressString', width:200}">收货地址</th>
      <th lay-data="{field:'tel', width:120}">联系电话</th>
      <th lay-data="{field:'paymenttime', width:160, templet: function(d){ return formatTime(d.paymenttime); }}">支付时间</th>
      <th lay-data="{toolbar:'#linetools', width:180, fixed: 'right'}">操作</th>
    </tr>
    </thead>
  </table>
</div>


<!--行内工具栏-->
<script id="linetools" type="text/html">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-normal" lay-event="detail">详情</button>
    <button class="layui-btn layui-btn-danger" lay-event="delete">删除</button>
    <button class="layui-btn layui-btn-warm" lay-event="edit">修改</button>
  </div>
</script>
<!--头部工具栏-->
<script id="toptools" type="text/html">
  <div class="layui-form-item">
    <div class="layui-input-inline">
      <input type="text" name="text"  placeholder="请输入查询内容" autocomplete="off" class="layui-input">
    </div>
    <div class="layui-input-inline">
      <button type="button" class="layui-btn" lay-event="check">查询</button>
    </div>
  </div>
</script>
<script type="text/html" id="isupsetTpl">
  {{#  if(d.isupset === 0){ }}
  否
  {{#  } else if(d.isupset === 1){ }}
  是
  {{#  } }}
</script>

<!-- 订单详细内容模板 -->
<script type="text/html" id="order-detail-template">
  {{# for(var i = 0; i < d.orderInfos.length; i++) { }}
  <div class="product-item">
    <img src="{{d.orderInfos[i].imgurl}}" alt="{{d.orderInfos[i].productname}}" class="product-image">
    <div class="product-info">
      <span class="product-name">商品名称: {{d.orderInfos[i].productname}}</span>
      <span class="product-category">商品类型: {{d.orderInfos[i].productcategory}}</span>
      <span class="product-price">商品单价价格: {{d.orderInfos[i].price}}</span>
      <span class="product-quantity">订货数量: {{d.orderInfos[i].quantity}}</span>
      <span class="product-description">商品描述: {{d.orderInfos[i].description}}</span>
    </div>
  </div>
  {{# } }}
</script>

<!-- 修改订单信息表单模板 -->
<script type="text/html" id="edit-order-template">
  <form class="layui-form" lay-filter="edit-order-form">
    <input type="hidden" name="orderid" value="{{d.orderid}}">
    <!-- 添加 userid 隐藏输入框 -->
    <input type="hidden" name="userid" value="{{d.userid}}">
    <!-- 添加 addressid 隐藏输入框 -->
    <input type="hidden" name="addressid" value="{{d.addressid}}">
    <!-- 添加 code 隐藏输入框 -->
    <input type="hidden" name="code" value="{{d.code}}">
    <div class="layui-form-item">
      <label class="layui-form-label">订单金额</label>
      <div class="layui-input-block">
        <input type="text" name="money" value="{{d.money}}" lay-verify="required" placeholder="请输入订单金额" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">订单状态</label>
      <div class="layui-input-block">
        <select name="status" lay-verify="required">
          <option value="待付款" {{ d.status === '待付款' ? 'selected' : '' }}>待付款</option>
          <option value="已付款" {{ d.status === '已付款' ? 'selected' : '' }}>已付款</option>
          <option value="商家已发货" {{ d.status === '商家已发货' ? 'selected' : '' }}>商家已发货</option>
          <option value="已收货" {{ d.status === '已收货' ? 'selected' : '' }}>已收货</option>
          <option value="已完成订单" {{ d.status === '已完成订单' ? 'selected' : '' }}>已完成订单</option>
        </select>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">是否上门安装</label>
      <div class="layui-input-block">
        <input type="radio" name="isupset" value="0" title="否" {{ d.isupset === 0 ? 'checked' : '' }}>
        <input type="radio" name="isupset" value="1" title="是" {{ d.isupset === 1 ? 'checked' : '' }}>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">收货地址</label>
      <div class="layui-input-block">
        <input type="text" name="address" value="{{d.address.address}}" lay-verify="required" placeholder="请输入收货地址" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">联系电话</label>
      <div class="layui-input-block">
        <input type="text" name="tel" value="{{d.address.tel}}" lay-verify="required" placeholder="请输入联系电话" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">用户姓名</label>
      <div class="layui-input-block">
        <input type="text" name="name" value="{{d.address.name}}" lay-verify="required" placeholder="请输入用户姓名" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">支付时间</label>
      <div class="layui-input-block">
        <input type="text" name="paymenttime" value="{{d.paymenttime}}" lay-verify="required" placeholder="请输入支付时间" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-input-block">
        <button class="layui-btn" lay-submit lay-filter="edit-order-submit">提交修改</button>
        <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
      </div>
    </div>
  </form>
</script>

<script src="layui/layui.all.js"></script>
<script>
  const $ = layui.$;
  const table = layui.table;
  const layer = layui.layer;
  const form = layui.form;

  // 获取订单数据并处理地址信息
  function getOrders() {
    $.ajax({
      url: 'order/getOrders',
      success: function (result) {
        if (result && result.data) {
          const allOrders = result.data;
          table.reload("datalist", {
            data: allOrders
          });
        } else {
          console.error('返回的数据格式不正确:', result);
          layer.msg('返回的数据格式不正确，请稍后重试', { icon: 2 });
        }
      },
      error: function (error) {
        console.error('获取订单列表失败:', error);
        layer.msg('获取订单列表失败，请稍后重试', { icon: 2 });
      }

    });
  }
  // 页面加载时获取订单数据
  getOrders();


  // 格式化时间函数
  function formatTime(isoTime) {
    const date = new Date(isoTime);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }


  // 行内按钮监听事件
  table.on("tool(datalist)", function(obj) {
    // 被点击按钮的lay-event属性值
    let event = obj.event;
    // 被点击按钮所在行的数据
    let data = obj.data;
    if (event === 'delete') {
      // 防止误操作
      layer.confirm("确认要删除吗？", function() {
        // 点击确认后要执行的代码
        console.log(data);
        $.ajax({
          url: 'order/delete',
          data: {id: data.orderid},
          success: function() {
            // 提示信息
            layer.msg("删除成功", {time: 1800, icon: 1});
            // 刷新表格信息
            getOrders();
          }
        });
      });
    } else if (event === 'detail') {
      // 获取订单详情
      $.ajax({
        url: `order/info/${data.orderid}`,
        success: function(result) {
          if (result.code === 200) {
            const orderInfos = result.data;
            const orderDetailPromises = orderInfos.map(item => {
              return new Promise((resolve, reject) => {
                // 调用获取商品信息的接口
                $.ajax({
                  url: `product/getproduct`,
                  data: { id: item.productid },
                  success: function (productResult) {
                    if (productResult.code === 0) {
                      const product = productResult.data;
                      // 将商品信息合并到订单信息中
                      const combinedItem = {
                        ...item,
                        productname: product.productname,
                        productcategory: product.productcategory,
                        price: product.price,
                        description: product.description,
                        imgurl: product.imgurl,
                        quantity: item.quantity
                      };
                      resolve(combinedItem);
                    } else {
                      reject(new Error('获取商品信息失败'));
                    }
                  },
                  error: function (error) {
                    reject(error);
                  }
                });
              });
            });

            // 等待所有商品信息请求完成
            Promise.all(orderDetailPromises)
                    .then(combinedOrderInfos => {
                      const template = $('#order-detail-template').text();
                      const render = layui.laytpl(template);
                      const html = render.render({ orderInfos: combinedOrderInfos, orderid: data.orderid, address: data.address });

                      // 弹出对话框显示订单详情
                      layer.open({
                        type: 1,
                        title: '订单详细内容',
                        content: `<div class="order-detail-dialog">${html}</div>`,
                        area: ['800px', '600px'],
                        scrollbar: false
                      });
                    })
                    .catch(error => {
                      console.error('获取商品信息失败:', error);
                      layer.msg('获取商品信息失败，请稍后重试', { icon: 2 });
                    });
          } else {
            layer.msg("获取订单详情失败", {time: 1800, icon: 2});
          }
        },
        error: function() {
          layer.msg("获取订单详情失败", {time: 1800, icon: 2});
        }
      });
    } else if (event === 'edit') {
      const template = $('#edit-order-template').text();
      const render = layui.laytpl(template);
      const html = render.render(data);

      layer.open({
        type: 1,
        title: '修改订单信息',
        content: html,
        area: ['400px', '500px'],
        success: function() {
          form.render();
        }
      });
    }
  });

  // 监听修改订单表单提交事件
  form.on('submit(edit-order-submit)', function(data) {
    $.ajax({
      url: 'order/update',
      type: 'POST',
      contentType: 'application/json', // 设置请求头 Content-Type 为 application/json
      data: JSON.stringify(data.field), // 将请求数据转换为 JSON 字符串
      success: function(result) {
        if (result.code === 200) {
          layer.msg('订单信息修改成功', { icon: 1 });
          layer.closeAll();
          getOrders();
        } else {
          layer.msg('订单信息修改失败: ' + result.msg, { icon: 2 });
        }
      },
      error: function(error) {
        layer.msg('订单信息修改失败，请稍后重试', { icon: 2 });
      }
    });
    return false;
  });

  // 头部按钮监听事件
  table.on("toolbar(datalist)", function(obj) {
    let event = obj.event;
    if (event === 'check') {
      // 获取输入框中的数据
      let text = $("[name='text']").val();
      // 发送到后端 layui表格加载
      getOrders();
      table.reload("datalist",{
        where:{text:text},
        page:{curr:1}
      });
    }
  });


</script>
</body>
</html>